﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Model.Util;
using Model.Util.DTO;
using Xproject.Framework.Core.Repositories;
using Xproject.Framework.Utility.Extensions;
namespace Repository.Util
{
   public static class UserCollectionRep
    {
        public static List<UserCollection> GetMyCollections(this IRepositoryAsync<UserCollection> repository, int offset, int limit, string userId)
        {
            string whereCondit = string.Format(@" where  1=1    " );
            if (!string.IsNullOrEmpty(userId))
            {
                whereCondit += string.Format(@" and   u.UserId = '{0}' ", userId);
            }
            string exeTotalSql = string.Format(@"
             declare   @TOTAL INT            
             select @TOTAL =count(u.CollectionId) from [WeiXin_BasicInfo].[dbo].[UserCollection] u        
                {0}
            ", whereCondit);

            string exeSql = string.Format(@"
      select * from ( 
              SELECT ROW_NUMBER() OVER(order by u.CreateTime desc) AS RowId,u.* 
                  ,@TOTAL AS Total 
             from [WeiXin_BasicInfo].[dbo].[UserCollection] u             
              {0}
            )  as b                      
         where RowId between {1} and {2} 
            ", whereCondit, (offset - 1) * limit, offset * limit);
            return repository.SqlQueryT<UserCollection>(exeTotalSql + exeSql).ToList();
        }

        public static UserCollection GetUserCollectionByRefId(this IRepositoryAsync<UserCollection> repository, string UserId,string RefId)
        {
            Expression<Func<UserCollection, bool>> express = i => i.UserId == UserId;
            if (!string.IsNullOrEmpty(RefId))
            {
                express = express.AndAlso(i => i.RefId == RefId);
            }
            else
            {
                return null;
            }
            return repository.Query().Where(express).Select().OrderByDescending(i => i.CreateTime).FirstOrDefault();
        }
    }
}

